<template>
  <div class="im-container">
    <!-- IM侧边栏 -->
    <div class="im-sidebar">
      <!-- 用户信息 -->
      <div class="user-info">
        <el-avatar :src="imStore.currentUser?.avatar" :size="40">
          {{ imStore.currentUser?.nickname?.charAt(0) }}
        </el-avatar>
        <div class="user-details">
          <div class="username">{{ imStore.currentUser?.nickname }}</div>
          <div class="status" :class="imStore.isConnected ? 'online' : 'offline'">
            {{ imStore.isConnected ? '在线' : '离线' }}
          </div>
        </div>
      </div>

      <!-- 搜索框 -->
      <div class="search-box">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索好友或群组"
          prefix-icon="Search"
          clearable
        />
      </div>

      <!-- 标签页 -->
      <el-tabs v-model="activeTab" class="im-tabs">
        <el-tab-pane label="好友" name="friends">
          <div class="contact-list">
            <div
              v-for="friend in filteredFriends"
              :key="friend.userId"
              class="contact-item"
              :class="{ active: imStore.currentChat?.id === friend.userId }"
              @click="selectChat('user', friend.userId, friend.nickname, friend.avatar)"
            >
              <el-avatar :src="friend.avatar" :size="36">
                {{ friend.nickname?.charAt(0) }}
              </el-avatar>
              <div class="contact-info">
                <div class="contact-name">{{ friend.nickname }}</div>
                <div class="contact-status" :class="friend.status">
                  {{ getStatusText(friend.status) }}
                </div>
              </div>
              <el-badge v-if="getUnreadCount(friend.userId) > 0" :value="getUnreadCount(friend.userId)" />
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="群组" name="groups">
          <div class="contact-list">
            <div
              v-for="group in filteredGroups"
              :key="group.groupId"
              class="contact-item"
              :class="{ active: imStore.currentChat?.id === group.groupId }"
              @click="selectChat('group', group.groupId, group.groupName, group.avatar)"
            >
              <el-avatar :src="group.avatar" :size="36">
                {{ group.groupName?.charAt(0) }}
              </el-avatar>
              <div class="contact-info">
                <div class="contact-name">{{ group.groupName }}</div>
                <div class="contact-desc">{{ group.memberCount }} 人</div>
              </div>
              <el-badge v-if="getUnreadCount(group.groupId) > 0" :value="getUnreadCount(group.groupId)" />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 聊天区域 -->
    <div class="im-main">
      <div v-if="!imStore.currentChat" class="welcome">
        <el-empty description="选择一个好友或群组开始聊天" />
      </div>
      
      <div v-else class="chat-area">
        <!-- 聊天头部 -->
        <div class="chat-header">
          <div class="chat-info">
            <el-avatar :src="imStore.currentChat.avatar" :size="32">
              {{ imStore.currentChat.name?.charAt(0) }}
            </el-avatar>
            <div class="chat-details">
              <div class="chat-name">{{ imStore.currentChat.name }}</div>
              <div class="chat-type">{{ imStore.currentChat.type === 'user' ? '私聊' : '群聊' }}</div>
            </div>
          </div>
          <div class="chat-actions">
            <el-button type="text" icon="More" @click="showChatMenu = true" />
          </div>
        </div>

        <!-- 消息列表 -->
        <div class="message-list" ref="messageListRef">
          <div
            v-for="message in imStore.messages"
            :key="message.messageId"
            class="message-item"
            :class="{ 'own-message': message.fromUserId === imStore.currentUser?.userId }"
          >
            <div class="message-content">
              <div class="message-text">{{ message.content }}</div>
              <div class="message-time">{{ formatTime(message.timestamp) }}</div>
            </div>
          </div>
        </div>

        <!-- 消息输入 -->
        <div class="message-input">
          <el-input
            v-model="newMessage"
            type="textarea"
            :rows="3"
            placeholder="输入消息..."
            @keydown.enter.prevent="sendMessage"
          />
          <div class="input-actions">
            <el-button type="text" icon="Picture" @click="selectFile" />
            <el-button type="text" icon="Microphone" @click="startVoice" />
            <el-button type="primary" @click="sendMessage" :disabled="!newMessage.trim()">
              发送
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 群组菜单 -->
    <el-drawer v-model="showChatMenu" title="聊天设置" direction="rtl">
      <div class="chat-menu">
        <el-button type="primary" @click="createGroup">创建群组</el-button>
        <el-button @click="loadMessageHistory">加载历史消息</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { useImStore } from '@/store/modules/im'
import { sendMessage, sendGroupMessage, createGroup, getMessageHistory } from '@/api/im'

const imStore = useImStore()

// 响应式数据
const searchKeyword = ref('')
const activeTab = ref('friends')
const newMessage = ref('')
const showChatMenu = ref(false)
const messageListRef = ref<HTMLElement>()

// 计算属性
const filteredFriends = computed(() => {
  if (!searchKeyword.value) return imStore.friends
  return imStore.friends.filter(friend => 
    friend.nickname?.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

const filteredGroups = computed(() => {
  if (!searchKeyword.value) return imStore.groups
  return imStore.groups.filter(group => 
    group.groupName?.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

// 方法
const getStatusText = (status: string) => {
  const statusMap = {
    online: '在线',
    offline: '离线',
    busy: '忙碌',
    away: '离开'
  }
  return statusMap[status] || '未知'
}

const getUnreadCount = (id: string) => {
  // 这里可以根据实际需求计算未读消息数
  return 0
}

const selectChat = (type: 'user' | 'group', id: string, name: string, avatar?: string) => {
  console.log('选择聊天 - 类型:', type, 'ID:', id, '名称:', name)
  const chatObj = { type, id, name, avatar }
  console.log('设置当前聊天对象:', chatObj)
  imStore.setCurrentChat(chatObj)
  imStore.markAsRead(id)
  scrollToBottom()
}

const sendMessage = async () => {
  if (!newMessage.value.trim() || !imStore.currentChat) return

  console.log('发送消息 - 当前聊天对象:', imStore.currentChat)
  console.log('发送消息 - 当前聊天类型:', imStore.currentChat?.type)
  console.log('发送消息 - 当前聊天ID:', imStore.currentChat?.id)
  console.log('发送消息 - 消息内容:', newMessage.value)

  try {
    const messageContent = newMessage.value.trim()
    newMessage.value = ''

    // 添加消息到本地列表（乐观更新）
    const newMsg = {
      messageId: Date.now().toString(),
      fromUserId: imStore.currentUser?.userId || '',
      toUserId: imStore.currentChat.type === 'user' ? imStore.currentChat.id : undefined,
      groupId: imStore.currentChat.type === 'group' ? imStore.currentChat.id : undefined,
      content: messageContent,
      messageType: 'text' as const,
      timestamp: new Date().toISOString(),
      status: 'sending' as const
    }
    imStore.addMessage(newMsg)
    scrollToBottom()

    // 根据聊天类型调用不同的API
    let response
    if (imStore.currentChat.type === 'user') {
      console.log('发送私聊消息 - 参数:', {
        toUserId: imStore.currentChat.id,
        content: messageContent,
        messageType: 'text'
      })
      // 发送私聊消息
      response = await sendMessage({
        toUserId: imStore.currentChat.id,
        content: messageContent,
        messageType: 'text'
      })
    } else {
      console.log('发送群聊消息 - 参数:', {
        groupId: imStore.currentChat.id,
        content: messageContent,
        messageType: 'text'
      })
      // 发送群聊消息
      response = await sendGroupMessage({
        groupId: imStore.currentChat.id,
        content: messageContent,
        messageType: 'text'
      })
    }

    console.log('发送消息 - API响应:', response)

    if (response.code === 200) {
      // 发送成功，更新消息状态
      newMsg.status = 'sent'
      if (response.data && response.data.messageId) {
        newMsg.messageId = response.data.messageId
      }
      ElMessage.success('消息发送成功')
    } else {
      // 发送失败，更新消息状态
      newMsg.status = 'failed'
      ElMessage.error('消息发送失败: ' + response.msg)
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败: ' + error.message)
    // 更新消息状态为失败
    if (imStore.messages.length > 0) {
      const lastMessage = imStore.messages[imStore.messages.length - 1]
      if (lastMessage.status === 'sending') {
        lastMessage.status = 'failed'
      }
    }
  }
}

const scrollToBottom = () => {
  nextTick(() => {
    if (messageListRef.value) {
      messageListRef.value.scrollTop = messageListRef.value.scrollHeight
    }
  })
}

const formatTime = (timestamp: string) => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

const selectFile = () => {
  // 文件选择逻辑
  ElMessage.info('文件选择功能待实现')
}

const startVoice = () => {
  // 语音录制逻辑
  ElMessage.info('语音录制功能待实现')
}

const createGroup = () => {
  // 创建群组逻辑
  ElMessage.info('创建群组功能待实现')
}

const loadMessageHistory = async () => {
  if (!imStore.currentChat) return

  try {
    const response = await getMessageHistory({
      targetId: imStore.currentChat.id,
      pageNum: 1,
      pageSize: 20
    })

    if (response.code === 200) {
      // 加载历史消息
      ElMessage.success('历史消息加载成功')
    }
  } catch (error) {
    console.error('加载历史消息失败:', error)
    ElMessage.error('加载历史消息失败')
  }
}

// 生命周期
onMounted(async () => {
  // 登录IM系统
  const loginSuccess = await imStore.login()
  if (!loginSuccess) {
    ElMessage.error('IM系统连接失败')
  }
})

// 使用系统已有的全局WebSocket连接，不需要单独创建

const handleWebSocketMessage = (data) => {
  console.log('收到WebSocket消息:', data)
  
  switch (data.type) {
    case 'new_message':
      // 收到新私聊消息
      console.log('收到私聊消息:', data)
      imStore.addMessage({
        id: data.messageId,
        fromUserId: data.fromUserId,
        toUserId: data.toUserId,
        content: data.content,
        messageType: data.messageType,
        createTime: data.createTime,
        senderName: data.senderName,
        senderAvatar: data.senderAvatar
      })
      break
    case 'new_group_message':
      // 收到新群聊消息
      console.log('收到群聊消息:', data)
      imStore.addMessage({
        id: data.messageId,
        fromUserId: data.fromUserId,
        content: data.content,
        messageType: data.messageType,
        createTime: data.createTime,
        senderName: data.senderName,
        senderAvatar: data.senderAvatar,
        groupId: data.groupId
      })
      break
    case 'group_notification':
      // 收到群聊通知
      console.log('收到群聊通知:', data)
      ElMessage.info(data.content)
      break
    case 'message':
      // 兼容旧的消息类型
      imStore.addMessage(data)
      break
    case 'typing':
      // 正在输入状态
      console.log('用户正在输入:', data)
      break
    case 'user_status':
      // 用户状态变更
      updateUserStatus(data)
      break
    default:
      console.log('收到未知消息类型:', data.type)
  }
}

const updateUserStatus = (data) => {
  // 更新用户状态
  const user = imStore.friends.find(f => f.userId === data.userId)
  if (user) {
    user.status = data.imStatus || data.status
  }
}
</script>

<style scoped>
.im-container {
  display: flex;
  height: 100vh;
  background: #f5f5f5;
}

.im-sidebar {
  width: 300px;
  background: white;
  border-right: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
}

.user-info {
  padding: 16px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #e0e0e0;
}

.user-details {
  margin-left: 12px;
  flex: 1;
}

.username {
  font-weight: 500;
  color: #333;
}

.status {
  font-size: 12px;
  color: #999;
}

.status.online {
  color: #67c23a;
}

.search-box {
  padding: 16px;
  border-bottom: 1px solid #e0e0e0;
}

.im-tabs {
  flex: 1;
  overflow: hidden;
}

.contact-list {
  height: 100%;
  overflow-y: auto;
}

.contact-item {
  padding: 12px 16px;
  display: flex;
  align-items: center;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.2s;
}

.contact-item:hover {
  background: #f5f5f5;
}

.contact-item.active {
  background: #e6f7ff;
  border-right: 3px solid #1890ff;
}

.contact-info {
  margin-left: 12px;
  flex: 1;
}

.contact-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.contact-desc,
.contact-status {
  font-size: 12px;
  color: #999;
}

.im-main {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.welcome {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-header {
  padding: 16px;
  background: white;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.chat-info {
  display: flex;
  align-items: center;
}

.chat-details {
  margin-left: 12px;
}

.chat-name {
  font-weight: 500;
  color: #333;
}

.chat-type {
  font-size: 12px;
  color: #999;
}

.message-list {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background: #fafafa;
}

.message-item {
  margin-bottom: 16px;
  display: flex;
}

.message-item.own-message {
  justify-content: flex-end;
}

.message-content {
  max-width: 70%;
  background: white;
  padding: 12px 16px;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.own-message .message-content {
  background: #1890ff;
  color: white;
}

.message-text {
  margin-bottom: 4px;
  word-wrap: break-word;
}

.message-time {
  font-size: 12px;
  opacity: 0.7;
}

.message-input {
  padding: 16px;
  background: white;
  border-top: 1px solid #e0e0e0;
}

.input-actions {
  margin-top: 8px;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.chat-menu {
  padding: 16px;
}

.chat-menu .el-button {
  width: 100%;
  margin-bottom: 8px;
}
</style>
